package org.hot100.h042;

/**
 * @Author: wjy
 * @Date: 2021/12/15 9:08
 */
public class Solution {

    public static void main(String[] args) {

        int[] ints = {0,1,0,2,1,2,1,3,2,1,2,1,1};
        //int[] ints = {4,2,0,3,2,5};
        //int[] ints = {0,1,0,2,1,0,1,3,2,1,2,1};
        //int[] ints = {5,4,1,2};

        Solution solution = new Solution();
        System.out.println(solution.trap(ints));

    }

    /**
     * hard!!!
     * @param height
     * @return
     */
    public int trap(int[] height) {
        int sum = 0;
        int[] max_left = new int[height.length];
        int[] max_right = new int[height.length];

        for (int i = 1; i < height.length; i++) {
            max_left[i] = Math.max(max_left[i - 1], height[i - 1]);
        }
        for (int i = height.length - 2; i >= 0; i--) {
            max_right[i] = Math.max(max_right[i + 1], height[i + 1]);
        }
        for (int i = 1; i < height.length - 1; i++) {
            int min = Math.min(max_left[i], max_right[i]);
            if (min > height[i]) {
                sum = sum + (min - height[i]);
            }
        }
        return sum;
    }

}
